#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef struct file_t {
	char name[50];
	struct file_t* next;
} file_c;

file_c* initFileList();/*初始化文件链表*/
file_c* createNewNode();/*创建文件结点*/
int appendFile(file_c* files);/*向文件链表中添加文件*/
void destroyList(file_c** files);/*销毁文件链表，删除o文件*/
void createOFile(file_c* files);/*编译c文件，创建o文件*/
void createEXEFile(file_c* files);/*编译o文件，创建可执行文件*/

file_c* initFileList()
{
	file_c* files;
	files = (file_c*)malloc(sizeof(file_c));
	if (files == NULL)
		exit(0);
	files->next = NULL;
	return files;
}

file_c* createNewNode()
{
	file_c* new_file;
	new_file = (file_c*)malloc(sizeof(file_c));
	if (new_file == NULL)
		return NULL;
	scanf("%s", new_file->name);
	new_file->next = NULL;
	return new_file;
}

int appendFile(file_c* files)
{
	if (files == NULL)
		return -1;
	printf("C文件：");
	do {
		file_c* new_file;
		new_file = createNewNode();
		files->next = new_file;
		files = files->next;
	} while ('\n' != getchar());
	return 0;
}

void destroyList(file_c** files)
{
	if (files == NULL || *files == NULL)
		return;
	file_c* temp;
	while (*files != NULL) {
		temp = *files;
		*files = (*files)->next;
		remove(temp->name);
		free(temp);
	}
	*files = NULL;
}

void createOFile(file_c* files)
{
	if (files != NULL && files->next != NULL) {
		files = files->next;
		while (files != NULL) {
			char newName[50] = "\0";
			strcat(newName, files->name);
			newName[strlen(newName) - 1] = 'o';
			char gcc_o[100] = "gcc -c -o ";
			strcat(gcc_o, newName);
			strcat(gcc_o, " ");
			strcat(gcc_o, files->name);
			system(gcc_o);
			files->name[strlen(newName) - 1] = 'o';
			files = files->next;
		}
	}
}

void createEXEFile(file_c* files)
{
	if (files == NULL || files->next == NULL)
		return;
	printf("请输入“输出文件名”：");
	char gcc_exe[300] = "gcc -o ";
	char output[30];
	scanf("%s", output);
	strcat(gcc_exe, output);
	files = files->next;
	while (files != NULL) {
		strcat(gcc_exe, " ");
		strcat(gcc_exe, files->name);
		files = files->next;
	}
	system(gcc_exe);
}

int main()
{
	file_c* files;
	files = initFileList();
	appendFile(files);
	createOFile(files);
	createEXEFile(files);
	destroyList(&files);
	files = NULL;
	return 0;
}